package com.jiaai.cloud.wx.controller;


import com.jiaai.cloud.base.util.UploadUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 文件上传
 */

@RestController
public class UploadController {

     @RequestMapping("/upload/{directories}")
     public  Object upload(

                          @PathVariable(value = "directories",required = false)String  directories,
                          HttpServletRequest request) throws UnsupportedEncodingException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        Set<String> files=new HashSet<>();
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                String key=iter.next();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(key);
                String fileName= UploadUtil.copyFile(file,directories);
               // String url=URLEncoder.encode(UploadUtil.getHttpUrl(fileName,directories),"utf-8");
                files.add(UploadUtil.getHttpUrl(fileName,directories));
            }

        }

        return   files;
    }

}
